package com.pzl.library.base;

import java.util.ArrayList;

/**
 * Created by zl.peng on 2016-03-25.
 */
public class Node implements INode {
    protected Node parent;
    protected ArrayList<Node> children;
    protected int level;
    /**
     * 默认未选中
     */
    protected boolean isSelected = false;
    /**
     * 默认是否展开
     */
    protected boolean isExpand = true;

    public Node() {
        children = new ArrayList<Node>();
    }

    @Override
    public void addChild(Node node) {
        if (parent == null && level > 0)
            throw new IllegalStateException("can not add child ,because parent is null");
        node.setParent(this);
        node.setLevel(this.level + 1);
        children.add(node);
    }

    @Override
    public void removeChild(Node node) {
        children.remove(node);
    }

    @Override
    public void clear() {
        children.clear();
    }

    @Override
    public ArrayList<Node> treeToList() {
        ArrayList<Node> nodes = new ArrayList<Node>();
        nodes.add(this);
        if (isExpand == false && !(this instanceof Root)) return nodes;
        for (int i = 0; i < children.size(); i++) {
            Node child = children.get(i);
            if (child.isLeaf()) {
                nodes.add(child);
            } else {
                nodes.addAll(child.treeToList());
            }
        }
        return nodes;
    }

    @Override
    public boolean isLeaf() {
        return children.size() == 0 ? true : false;
    }


    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public boolean isExpand() {
        if (isLeaf()) {
            return false;
        }
        return isExpand;
    }

    public void setExpand(boolean expand) {
        if (isLeaf()) {
            isExpand = false;
            return;
        }
        isExpand = expand;
    }

    public ArrayList<Node> getChildren() {
        return children;
    }
}
